module.exports = {
  // 获取用户优惠券列表
  async getUserCoupons(userId, status = 'usable') {
    const db = uniCloud.database()
    const now = new Date()
    
    try {
      // 构建查询条件
      const where = {
        user_id: userId
      }
      
      if (status === 'usable') {
        where.status = 1
        where.valid_start = db.command.lte(now)
        where.valid_end = db.command.gte(now)
      } else if (status === 'used') {
        where.status = 2
      } else if (status === 'expired') {
        where.status = 1
        where.valid_end = db.command.lt(now)
      }
      
      // 获取优惠券数据
      const couponRes = await db.collection('user_coupon')
        .where(where)
        .field({
          coupon_id: true,
          status: true,
          valid_start: true,
          valid_end: true,
          use_time: true
        })
        .orderBy('valid_end', 'asc')
        .get()
      
      if (!couponRes.data || couponRes.data.length === 0) {
        return {
          code: 0,
          message: '获取优惠券成功',
          data: []
        }
      }
      
      // 获取优惠券详情
      const couponIds = couponRes.data.map(item => item.coupon_id)
      const couponDetailRes = await db.collection('coupon')
        .where({
          _id: db.command.in(couponIds)
        })
        .field({
          name: true,
          discount_type: true,
          value: true,
          min_amount: true,
          applicable_cell: true,
          stock: true
        })
        .get()
      
      const couponMap = {}
      couponDetailRes.data.forEach(coupon => {
        couponMap[coupon._id] = coupon
      })
      
      // 组合数据
      const coupons = couponRes.data.map(item => {
        const coupon = couponMap[item.coupon_id] || {}
        return {
          id: item._id,
          coupon_id: item.coupon_id,
          name: coupon.name || '优惠券',
          discount_type: coupon.discount_type || 0,
          value: coupon.value || 0,
          min_amount: coupon.min_amount || 0,
          applicable_cell: coupon.applicable_cell || [],
          valid_start: item.valid_start,
          valid_end: item.valid_end,
          use_time: item.use_time,
          status: item.status
        }
      })
      
      return {
        code: 0,
        message: '获取优惠券成功',
        data: coupons
      }
    } catch (e) {
      console.error('获取优惠券失败:', e)
      return {
        code: 500,
        message: '获取优惠券失败',
        data: null
      }
    }
  },
  
  // 领取优惠券
  async receiveCoupon(userId, couponId) {
    const db = uniCloud.database()
    
    try {
      // 检查优惠券是否存在
      const couponRes = await db.collection('coupon')
        .doc(couponId)
        .field({
          stock: true,
          valid_start: true,
          valid_end: true
        })
        .get()
      
      if (!couponRes.data || couponRes.data.length === 0) {
        return {
          code: 404,
          message: '优惠券不存在'
        }
      }
      
      const coupon = couponRes.data[0]
      
      // 检查库存
      if (coupon.stock <= 0) {
        return {
          code: 400,
          message: '优惠券已领完'
        }
      }
      
      // 检查是否已领取
      const existRes = await db.collection('user_coupon')
        .where({
          user_id: userId,
          coupon_id: couponId
        })
        .count()
      
      if (existRes.total > 0) {
        return {
          code: 400,
          message: '您已领取过此优惠券'
        }
      }
      
      // 开启事务
      const transaction = await db.startTransaction()
      
      // 1. 添加用户优惠券
      await transaction.collection('user_coupon').add({
        user_id: userId,
        coupon_id: couponId,
        status: 1, // 未使用
        valid_start: coupon.valid_start,
        valid_end: coupon.valid_end,
        receive_time: new Date()
      })
      
      // 2. 更新优惠券库存
      await transaction.collection('coupon').doc(couponId).update({
        stock: db.command.inc(-1)
      })
      
      // 提交事务
      await transaction.commit()
      
      return {
        code: 0,
        message: '领取优惠券成功'
      }
    } catch (e) {
      console.error('领取优惠券失败:', e)
      return {
        code: 500,
        message: '领取优惠券失败'
      }
    }
  }
}